package com.wang.security.filter;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.wang.common.result.ResponseUtil;
import com.wang.common.result.Result;
import com.wang.common.utils.JwtHelper;
import com.wang.security.custom.LoginInfoHelper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author wjh
 * @create 2023-05-27
 */

public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private StringRedisTemplate stringRedisTemplate;

    public TokenAuthenticationFilter(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //如果是登录接口，直接放行
        if ("/admin/system/index/login".equals(request.getRequestURI())){
            filterChain.doFilter(request,response);
            return;
        }

        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
        if (authentication != null){
            SecurityContextHolder.getContext().setAuthentication(authentication);
            filterChain.doFilter(request,response);
        } else {
            ResponseUtil.out(response, Result.error(208,"无用户信息"));
        }
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        //请求头里面是否有token
        String token = request.getHeader("token");
        if (StringUtils.isNotBlank(token)){
            String username = JwtHelper.getUsername(token);
            if (StringUtils.isNotBlank(username)){
                //当前用户信息放到ThreadLocal里
                LoginInfoHelper.setUserId(JwtHelper.getUserId(token));
                LoginInfoHelper.setUsername(username);
                //通过用户名称从redis中获取权限数据
                String json = (String) stringRedisTemplate.opsForValue().get("perms:"+username);
                //把redis中获取的JSON字符串转为SimpleGrantedAuthority集合类型
                if (StringUtils.isNotBlank(json)){
                    List<Map> maps = JSON.parseArray(json, Map.class);
                    System.out.println(maps);
                    List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
                    for (Map map : maps) {
                        String authority = (String) map.get("authority");
                        authorityList.add(new SimpleGrantedAuthority(authority));
                    }
                    return new UsernamePasswordAuthenticationToken(username,null, authorityList);
                }
                return new UsernamePasswordAuthenticationToken(username,null, Collections.emptyList());
            }
        }
        return null;
    }
}
